package com.xg.te.util;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;

/**
 * 反射工具类
 * 
 * @author liuguojun
 */
public class ReflectionUtils {

	private static final Logger logger = Logger
			.getLogger(ReflectionUtils.class);

	/**
	 * 实例化对象
	 * 
	 * @param className
	 * @return
	 */
	public static Object newInstance(final String className) {
		try {
			return Class.forName(className).newInstance();
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * 执行对象中的方法
	 * 
	 * @param object
	 * @param methodName
	 * @param parameterTypes
	 * @param parameters
	 * @return
	 */
	public static Object invokeMethod(final Object object,
			final String methodName, final Class<?>[] parameterTypes,
			final Object[] parameters) {
		Method method = getDeclaredMethod(object, methodName, parameterTypes);
		if (method == null) {
			throw new IllegalArgumentException("Could not find method ["
					+ methodName + "] on target [" + object + "]");
		}

		method.setAccessible(true);

		try {
			return method.invoke(object, parameters);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return null;
	}

	/**
	 * 循环向上转型, 获取对象的DeclaredMethod.
	 * 
	 * 如向上转型到Object仍无法找到, 返回null.
	 */
	protected static Method getDeclaredMethod(Object object, String methodName,
			Class<?>[] parameterTypes) {
		for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
				.getSuperclass()) {
			try {
				return superClass.getDeclaredMethod(methodName, parameterTypes);
			} catch (NoSuchMethodException ex) {
				logger.error(ex.getMessage(), ex);
			}
		}
		return null;
	}

}
